package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }


    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }


    @Override
    public void updateInstanceId(Long auditId, String instanceId) {

        carPackageAuditMapper.updateInstanceId(auditId, instanceId);
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        //通过id 将 套餐审核对象 取出来
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        //判断当前流程是否启动
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = null;
        //判断他是否是审核中的  是 就将审核点进行高亮处理
        if (audit.getStatus() == CarPackageAudit.STATUS_IN_ROGRESS) {
            //启动--高亮显示
            Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();

            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());
            inputStream = generator.generateDiagram(model, activeActivityIds, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        } else {
            //没启动--没有高亮显示
            //图片
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        }
        return inputStream;

    }


    @Autowired
    private ServiceItemServiceImpl serviceItemService;


    @Override
    // 套餐审核撤销
    public void cancelApply(Long id) {
        //注意 审核套餐撤销 要把审核状态恢复成初始化 审核状态改成撤销，审批流程实例要删除

        // 获取套餐审核对象
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (audit == null || audit.getStatus() != CarPackageAudit.STATUS_IN_ROGRESS) {
            throw new BusinessException("只有审核中才能撤销");
        }
        // 服务套餐初始化
        serviceItemService.changAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);

        // 审核记录状态改成 审核撤销
        carPackageAuditMapper.changAuditStatus(id, CarPackageAudit.STATUS_CANCEL);

        // activiti 流程停止
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "审核撤销");

    }

    @Override
    public void audit(Long id, int auditStatus, String info) {
        //服务套餐必须是审核中才允许审批 且通过套餐id查询出来不为空
        // 通过套餐id查询 套餐信息
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);


        if (audit == null || audit.getStatus() != CarPackageAudit.STATUS_IN_ROGRESS) {
            throw new BusinessException("只有审核中才允许进行审批");
        }

        //处理审核记录信息 （carPackageAudit）--具体审核信息
        String userName = ShiroUtils.getUser().getUserName();
        //STATUS_PASS审核通过
        if (auditStatus == CarPackageAudit.STATUS_PASS) {
            // 通过  设置审核记录
            audit.setAuditRecord(audit.getAuditRecord() + "<br>" + userName + "【同意】,批注意见：" + info);
        } else {
            // 拒绝
            audit.setAuditRecord(audit.getAuditRecord() + "<br>" + userName + "【拒绝】,批注意见：" + info);
        }
        // 推动流程--执行处理当前节点
        // 创建 任务查询 通过获取实例 ID获取 当前任务
        Task currentTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        // 设置审核状态，让排他网关决定走--通过/拒绝流程
        taskService.setVariable(currentTask.getId(), "auditStatus", auditStatus);
        // activiti 备注表中记录审核备注
        taskService.addComment(currentTask.getId(), audit.getInstanceId(), info);
        // 处理节点 -- 推动流程
        taskService.complete(currentTask.getId());

        // 查询下一个节点有没有值 一旦节点complete 流程自动往下移
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();



        if (auditStatus == CarPackageAudit.STATUS_PASS) {
            //2 审核通过做啥
            // 审核通过涉及俩个分支
            //      店长审核通过且--并且价格大于3000--走财务审核--状态不会变动
            //      财务审核通过--流程结束--状态都会变
            //怎么知道当前节点是店长还是财务审核？
            //处理完当前节点，马上获取下一个节点


            //2.1 获取下一个节点，判断该节点是否为null
            if(nextTask == null){
                //如果为null，当前流程结束了
                //  服务套餐（serviceItem）状态为审核通过
                serviceItemService.changAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                //  审核记录信息（carPackageAudit）转台为审核通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
            }else {
                //如果不为null，表示当前节点为店长审核，下一个节点是财务审核
                //  当前审核流程没有完成，所有对象状态不需要改动，还是审核中
                //  审核记录信息（carPackageAudit）当前的审核该为，财务审核负责人
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee())); //字符串转成long类型


            }
        } else {
            //3 审核拒绝-做啥
            // 服务状态改为：初始化
            serviceItemService.changAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            // 审核记录信息改为：审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }

        //   审核记录信息（carPackageAudit）当前的审核时间，new Dated()
        // 每次审核都记录审核时间
        audit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }

}
